/**
 * @description 自定义路由拦截
 */
import {
	getAuthorization
} from './auth.js';
import dayjs from 'dayjs';
import {
	expireTime,
	timeFormatter
} from '@/config/index.js';
// 白名单
const whiteList = ['/pages/index/index', {
			pattern: /^\/pages\/login\/*/
		} // 支持正则表达式
	],
	// uni.navigateTo, uni.redirectTo, uni.reLaunch, uni.switchTab这4个路由方法添加拦截器
	list = ['navigateTo', 'redirectTo', 'reLaunch', 'switchTab'];
export const isExpireFun = async () => {
	const res = await new Promise((resolve, reject) => {
		uni.request({
			url: 'http://api.m.taobao.com/rest/api3.do?api=mtop.common.getTimestamp',
			success({
				data
			}) {
				const {
					data: {
						t
					}
				} = data;
				const currentDate = dayjs(new Date(Number(t)));
				if (dayjs(expireTime, timeFormatter).isBefore(currentDate)) {
					// uni.reLaunch({
					// 	url: '/pages/expire/expire'
					// })
					resolve(true);
				} else {
					resolve(false);
				};
			},
			fail(err) {
				uni.showModal({
					content: err
				})
			}
		})
	});
	return res;
}
export default async function() {
	list.forEach(item => {
		// 页面跳转前进行拦截, invoke根据返回值进行判断是否继续执行跳转
		uni.addInterceptor(item, {
			invoke(e) {
				// 获取要跳转的页面路径（url去掉"?"和"?"后的参数）
				const url = e.url.split('?')[0];
				// 判断当前窗口是白名单，如果是则不重定向路由
				let pass;
				if (whiteList) {
					pass = whiteList.some((item) => {
						if (typeof item === 'object' && item.pattern) return item.pattern.test(url);
						return url === item;
					})
				}
				// 不是白名单并且没有token
				if (!pass && !getAuthorization()) {
					uni.reLaunch({
						url: "/pages/login/login"
					})
					return false
				}
				return true
			},
			fail(err) { // 失败回调拦截
				console.log(err)
			}
		})
	})
}